<?php

declare(strict_types=1);

namespace App\Middleware;

use Hyperf\Context\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\Contract\TranslatorInterface;

/**
 * 语言设定-中间件
 */
readonly class TranslationMiddleware implements MiddlewareInterface
{
        public function __construct(private TranslatorInterface $translator)
        {
        }

        /**
         * 处理过程
         * @param ServerRequestInterface $request
         * @param RequestHandlerInterface $handler
         * @return ResponseInterface
         */
        public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
        {
                $this->translator->setLocale($this->getAcceptLanguage($request));
                return $handler->handle($request);
        }

        /**
         * 获取请求头指定接受语言
         * @param ServerRequestInterface $request
         * @return string
         */
        public function getAcceptLanguage(ServerRequestInterface $request): string
        {
                $strAcceptLanguage = null;
                if ($request->hasHeader('Accept-Language')) {
                        $strAcceptLanguage = strtolower(explode(',', $request->getHeaderLine('Accept-Language'))[0]);
                        if (in_array($strAcceptLanguage, ['zh-cn', 'zh_cn', 'zh', 'cn'])) {
                                $strAcceptLanguage = 'zh_CN';
                        }
                }
                return $strAcceptLanguage ?: 'zh_CN';
        }
}